package com.qijia.travel.app;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.qijia.travel.domain.TouristGroup;
import com.qijia.travel.helper.FileUploadHelper;
import com.qijia.travel.vo.ProgressInfo;

public class FileUploadManager extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String FILE_UPLOAD_JSP = "/jsp/FileUploadForm.jsp";

	private static final long MAX_LENGTH = 10 * 1024 * 1024L; // 10MB

	private static final int HTTP_REDUNDANT_LENGTH = 1024; // 1KB

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher(FILE_UPLOAD_JSP);
		rd.forward(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		//ProgressInfo pi = new ProgressInfo();

		try {
			this.doUpload(request);
		} catch (Exception e) {
			//pi.setInProgress(false);
			info("FileUploadServlet", "cancelled or interrupted!");
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	private String getFileName(String fileName) {
		return fileName.substring(fileName.lastIndexOf("\\") + 1);
	}

	private void doUpload(HttpServletRequest request) {
		FileUploadHelper helper = new FileUploadHelper();
		helper.setRequest(request);
		// helper.setSaveFileDir(saveFileDir);
		try {
			helper.work();
			List<String> fileNames = helper.getSavedFileName();

			Object groupId = helper.getParameterValue("touristGroupId");
			info("group id :" + groupId);
			GroupManager manager = new GroupManager();

			if (fileNames != null && fileNames.size() > 0) {
				String fileName = fileNames.get(0);
				TouristGroup touristGroup = new TouristGroup();
				touristGroup.setTouristFile(fileName);
				if (groupId instanceof String) {
					touristGroup.setTouristGroupId(Integer
							.parseInt((new String()) ));
					manager.updateTouristGroup(touristGroup);
				} else if (groupId instanceof Integer) {
					touristGroup.setTouristGroupId((Integer) groupId);
					manager.updateTouristGroup(touristGroup);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void doUpload(HttpServletRequest request, ProgressInfo pi)
			throws Exception {

		String fldName = "";
		FileItemStream item = null;
		BufferedInputStream stream = null;

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		if (isMultipart) {
			int filesSize = request.getContentLength() - HTTP_REDUNDANT_LENGTH;
			if (filesSize >= MAX_LENGTH) {
				String errorMsg = "Error: Current files size is " + filesSize
						/ (1024 * 1024) + "MB which has exceeded max " + "10MB";
				pi.setCompleted(true);
				pi.setErrorMsg(errorMsg);
				throw new Exception(errorMsg);
			}
			ServletFileUpload upload = new ServletFileUpload();
			upload.setHeaderEncoding("UTF-8");
			upload.setFileSizeMax(MAX_LENGTH);
			upload.setSizeMax(MAX_LENGTH);
			UploadListener uploadListener = new UploadListener(pi);
			upload.setProgressListener(uploadListener);
			// Parse the request
			FileItemIterator fIter = upload.getItemIterator(request);

			while (fIter.hasNext()) {
				item = fIter.next();
				fldName = item.getFieldName();
				info("FileUploadServlet", fldName + ", " + item.isFormField()
						+ ", " + item.getContentType() + ", " + item.getName()
						+ ", " + item.getHeaders());

				if (!item.isFormField()) {
					fldName = item.getFieldName();
					if (item.getName() == null
							|| "".equals(item.getName().trim())) {
						continue;
					}

					pi.setCurFileName(item.getName());
					pi.setUploadedFiles(pi.getUploadedFiles() + "<b>"
							+ item.getName() + "</b><br/>");

					stream = new BufferedInputStream(item.openStream());
					ByteArrayOutputStream bStream = new ByteArrayOutputStream();
					long bStreamLen = Streams.copy(stream, bStream, true);

					info("FileUploadServlet", this.getFileName(item.getName()));

					File file = new File(this.getFileName(item.getName()));
					if (file.exists()) {
						file.delete();
					}
					OutputStream out = new FileOutputStream(file);
					bStream.writeTo(out);

					info("FileUploadServlet", fldName
							+ " just was uploaded, len " + bStreamLen);
				}

			}
		}

	}

	public static void info(String clsName, String info) {
		info(new StringBuffer().append(clsName).append(", ").append(info)
				.toString());
	}

	public static void info(String info) {
		System.out.println("-->> " + info);
	}

}
